package com.outsourcing.bottle.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;

import com.aviary.android.feather.Constants;
import com.aviary.android.feather.FeatherActivity;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.util.Utility;
/**
 * 
 * @author 06peng
 *
 */
public class SetAvatarAndNameActivity extends BasicActivity implements BasicUIEvent, OnClickListener, Callback {
	
	private final int set_avatar_nickname = 1;
	private final int error = 2;
	private final int activity_result_aviary = 3;
	
	private Bitmap bitMap;
	private File picFile;
	private boolean hasImage;
	private final int activity_result_camara_with_data = 1006;
	private final int activity_result_pick_with_data = 18;
	
	private Handler handler;
	
	private RelativeLayout layout;
	private ImageView avatarView;
	private EditText nameView;
	private Button button;
	

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		setContentView(R.layout.register_setavatar_nickname);
		initWidget();
	}
	
	private void initWidget() {
		layout = (RelativeLayout) findViewById(R.id.splash_image_layout);
		layout.setOnClickListener(this);
		avatarView = (ImageView) findViewById(R.id.splash_image);
		nameView = (EditText) findViewById(R.id.splash_set_edit);
		button = (Button) findViewById(R.id.splash_set_button);
		button.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == layout) {
			doPickPhotoAction();
		} else if (v == button) {
			if (nameView.getText().toString().trim().equals("")) {
				onToast(getString(R.string.login_txt_register_set_username_error));
				return;
			} else if (!hasImage) {
				onToast(getString(R.string.login_txt_register_set_avatar_error));
				return;
			}
			UICore.eventTask(this, this, set_avatar_nickname, "", null);
		} 
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case set_avatar_nickname:
			setAvatarAndNickName();
			break;
		default:
			break;
		}
	}
	
	
	private void setAvatarAndNickName() {
		String url = UrlConfig.set_avatar_nickname;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("nickname", nameView.getText().toString().trim());
        try {
            HashMap<String, File> filesMap = new HashMap<String, File>();
            if (picFile != null) {
    			filesMap.put("pic", picFile);
    		}
            String result = HttpUtils.post(url, paramsMap, filesMap);
            JSONObject object = new JSONObject(result);
        	JSONObject resultObj = object.getJSONObject("results");
        	int success = resultObj.getInt("success");
        	if (success == 0) {
        		String errmsg = resultObj.getString("errmsg");
        		Message msg = Message.obtain(handler, error, errmsg);
        		handler.sendMessage(msg);
        	} else {
        		String successmsg = resultObj.getString("successmsg");
				Message msg = Message.obtain(handler, set_avatar_nickname, successmsg);
				handler.sendMessage(msg);
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case set_avatar_nickname:
			Intent intent = new Intent(this, HomeActivity.class);
			startActivity(intent);
			break;
		case error:
			onToast(msg.obj.toString());
			break;
		default:
			break;
		}
		return false;
	}
	
	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
		    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		    File pictureFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
            if (!pictureFileDir.exists()) {
                pictureFileDir.mkdirs();
            }
            picFile = new File(pictureFileDir, "upload.jpeg");
            Uri pictureUri = Uri.fromFile(picFile);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
            startActivityForResult(cameraIntent, activity_result_camara_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 从本地手机中选择图片
	 */
//	private void doSelectImageFromLoacal(){
//		Intent localIntent = new Intent();
//		localIntent.setType("image/*");
//		localIntent.setAction("android.intent.action.GET_CONTENT");
//        Intent localIntent2 = Intent.createChooser(localIntent, getString(R.string.expand_edit_choose_photo));
//        startActivityForResult(localIntent2, activity_result_pick_with_data);
//	}
	
	// 封装请求Gallery的intent
	public Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		return intent;
	}
	
	// 请求Gallery程序
	protected void doPickPhotoFromGallery() {
		try {
			// Launch picker to choose photo for selected contact
			final Intent intent = getPhotoPickIntent();
			startActivityForResult(intent, activity_result_pick_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	protected void doCropPhoto(File f) {
		try {
			// 启动gallery去剪辑这个照片
			final Intent intent = getCropImageIntent(Uri.fromFile(f));
			startActivityForResult(intent, activity_result_pick_with_data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	* Constructs an intent for image cropping. 调用图片剪辑程序
	*/
	public Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		return intent;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Bitmap oldBitmap = bitMap;
		switch (requestCode) {
		case activity_result_pick_with_data: //从本地选择图片
			if (data == null) {
				return;
			}
			bitMap = data.getParcelableExtra("data");
            try {
                File pictureFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
                if (!pictureFileDir.exists()) {
                    pictureFileDir.mkdirs();
                }
                picFile = new File(pictureFileDir, "upload.jpeg");
                FileOutputStream ous = new FileOutputStream(picFile);
                bitMap.compress(Bitmap.CompressFormat.JPEG, 100, ous);
                
            	if ( !Utility.isExternalStorageAvilable() ) {
    				return;
    			}
    			Uri fileUri = Uri.fromFile(picFile);
    			Intent newIntent = new Intent( this, FeatherActivity.class );
    			newIntent.putExtra( "From_Type", Constants.ACTIVITY_AVATAR );
    			newIntent.setData( fileUri );
    			newIntent.putExtra( "API_KEY", Utility.API_KEY );

    			newIntent.putExtra( "output", Uri.parse( "file://" + picFile.getAbsolutePath() ) );
    			newIntent.putExtra( Constants.EXTRA_OUTPUT_FORMAT, Bitmap.CompressFormat.JPEG.name() );
    			newIntent.putExtra( Constants.EXTRA_OUTPUT_QUALITY, 100 );
    			newIntent.putExtra( Constants.EXTRA_TOOLS_DISABLE_VIBRATION, true );

    			final DisplayMetrics metrics = new DisplayMetrics();
    			getWindowManager().getDefaultDisplay().getMetrics( metrics );
    			int max_size = Math.min( metrics.widthPixels, metrics.heightPixels );
    			max_size = (int) ( (double) max_size / 0.8 );
    			newIntent.putExtra( "max-image-size", max_size );
    			newIntent.putExtra( "effect-enable-borders", true );
    			startActivityForResult(newIntent, activity_result_aviary );
    			if (oldBitmap != null && !oldBitmap.isRecycled()) {
    				oldBitmap.recycle();
    				oldBitmap = null;
    			}
                
            } catch (Exception e) {
                e.printStackTrace();
            }
			break;
		case activity_result_camara_with_data:  //拍照
			if (picFile == null) {
				File pictureFileDir = new File(
						Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
				picFile = new File(pictureFileDir, "upload.jpeg");
			}
			doCropPhoto(picFile);
			break;
		case activity_result_aviary:
			if (resultCode == RESULT_OK) {
				try {
					File pictureFileDir = new File(Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
		            if (!pictureFileDir.exists()) {
		                pictureFileDir.mkdirs();
		            }
		            picFile = new File(pictureFileDir, "upload.jpeg");

		            FileInputStream in = new FileInputStream(picFile);
					BitmapFactory.Options options1 = new BitmapFactory.Options();
					options1.inPurgeable = true;
					options1.inInputShareable = true;
					options1.inSampleSize = 2;
					try {
						BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options1, true);
					} catch (Exception ex) {
						ex.printStackTrace();
					}
					WeakReference<Bitmap> bitmapResult = new WeakReference<Bitmap>(BitmapFactory
							.decodeStream(in, null, options1));
					Bitmap bt = bitmapResult.get();
					findViewById(R.id.splash_image_camera).setVisibility(View.GONE);
		            avatarView.setImageBitmap(bt);
		            hasImage = true;
						
				} catch (Exception e) {
					e.printStackTrace();
				} finally{
				}
			}
			break;
		}
	}
	
	
	
	
	private void doPickPhotoAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		String[] choices;
		choices = new String[2];
		choices[0] = getString(R.string.expand_edit_take_photo); // 拍照
		choices[1] = getString(R.string.expand_edit_choose_photo); // 从相册中选择
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.expand_edit_photo_title);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						switch (which) {
						case 0:
							String status = Environment.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								doTakePhoto();// 用户点击了从照相机获取
							}
							break;
						case 1:
							doPickPhotoFromGallery();// 从相册中去获取
							break;
						}
					}
				});
		builder.setNegativeButton(cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}

				});
		builder.create().show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		try {
			if (bitMap != null && !bitMap.isRecycled()) {
				bitMap.recycle();
				bitMap = null;
				hasImage = false;
				
				File uploadFileDir = new File(
						Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
				File file = new File(uploadFileDir, "upload.jpeg");
				if (file.exists()) {
					file.delete();
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
